package de.blitzcoder.collide.gui.codetree;

import de.blitzcoder.collide.gui.BlitzMaxCodeDocument;
import de.blitzcoder.collide.gui.CodeDocument;
import de.blitzcoder.collide.gui.Document;
import de.blitzcoder.collide.gui.DocumentManager;
import de.blitzcoder.collide.gui.DocumentManagerListener;
import de.blitzcoder.collide.gui.ParserListener;
import java.awt.GridLayout;
import java.util.HashMap;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;



/**
 *
 * @author blitzcoder
 */
public class CodeTree extends JPanel implements DocumentManagerListener,ParserListener {

    // Saves the Trees
    private HashMap<BlitzMaxCodeDocument,Tree> treeViews;

    // Constant
    private final JLabel NOCODE = new JLabel("No Code");

    public CodeTree(DocumentManager manager) {
        manager.addDocumentManagerListener(this);
        treeViews = new HashMap<BlitzMaxCodeDocument, Tree>();
        setLayout(new GridLayout());
        setTree(NOCODE);
    }

    @Override
    public void documentAdded(Document doc) {
        doc = convertCloned(doc);
        if (doc instanceof BlitzMaxCodeDocument) {
            BlitzMaxCodeDocument codeDoc = (BlitzMaxCodeDocument) doc;
            codeDoc.addParserListener(this);
            Tree tree = new Tree();
            treeViews.put(codeDoc, tree);
            tree.fill(codeDoc.getParser().getResult());
        }
    }

    @Override
    public void documentRemoved(Document doc) {
        doc = convertCloned(doc);
        if (doc instanceof BlitzMaxCodeDocument) {
            BlitzMaxCodeDocument codeDoc = (BlitzMaxCodeDocument) doc;
            codeDoc.removeParserListener(this);
            treeViews.remove(codeDoc);
        }
        if (treeViews.size() == 0)
            setTree(NOCODE);
    }

    @Override
    public void documentSelected(Document doc) {
        doc = convertCloned(doc);
        if (doc instanceof BlitzMaxCodeDocument) {
            BlitzMaxCodeDocument codeDoc = (BlitzMaxCodeDocument) doc;
            Tree tree = treeViews.get(codeDoc);
            setTree(tree);
        } else {
            setTree(NOCODE);
        }
    }

    private Document convertCloned(Document doc) {
        if (doc.isClone())
            return doc.getOriginal();
        return doc;
    }

    private void setTree(final JComponent comp) {
        System.out.println("Removing");
        if (getComponentCount() > 0)
            remove(0);
        System.out.println("Adding");
        add(new JScrollPane(comp));
        updateUI();
    }

    @Override
    public void parserUpdate(CodeDocument document) {
        if (document instanceof BlitzMaxCodeDocument) {
            BlitzMaxCodeDocument codeDoc = (BlitzMaxCodeDocument) document;
            treeViews.get(codeDoc).fill(codeDoc.getParser().getResult());
        }
    }



}
